<?php 

class SearchPresenter extends BasePresenter{
	
	
	private $model;
	private $messages = array();
	/**
	 * Start lifecycle presenter
	 *
	 * @return void
	 */
	protected function startup(){
		parent::startup();
		
		$this->model = SearchModel::getInstance();
	}

	/**
	 * Settings for all render
	 *
	 * @return void
	 */
	protected function beforeRender(){

	}
	
	public function boxHTML($id){
		
		$link = $this->link("Search:", array("id"=>$id));

		$template = new Template();
		$template->registerFilter(new LatteFilter);
		$template->translation = Translation::getInstance()->getStaticTranslation();
		$template->link = $link;
		$template->setFile(APP_DIR."/templates/Search/box.phtml");
		
		return $template;
	}
	
	public function boxHTML2($id){
		
		return false;
	}
	
	public function getMessages(){
		
		return $this->messages;
	}
	
	/**
	 * Render default action
	 *
	 * @return void
	 */
	public function renderDefault($id){
		
		$system = SystemModel::getInstance();
		$lang = $system->getCurrentLanguage();

		$search = $this->model->fetchSearch();
		$results = array();
		
		foreach($search as $s){
			$data = unserialize($s["data"]);
			
			$object = new $data["presenter"];
			
			if(method_exists($object, "getSearchData")){
				$data = $object->getSearchData();
				$sql = $object->getSearchSql();
				
				foreach($data["cond"] as $c){
					$sql->where($c . " LIKE %s", '%'.$_POST["q"].'%');
				}
				
				// podminka pro aktualni jazyk
				$sql->and("m.id_language = %i", $lang[0]["id_language"]);
				
				foreach($sql as $key => $row){
					
					$args = (array) $row;
					
					if(array_key_exists("searchText", $args)){
						$searchText = $args["searchText"];
						unset($args["searchText"]);
					}
					
					if(array_key_exists("searchName", $args)){
						$searchName = $args["searchName"];
						unset($args["searchName"]);
					}
					
					$tmp_link = $this->getPresenter()->link($data["presenter"] . ":", $args);
					
					// upravime vzhled vyrazu v textu
					$exp = $this->explodei($_POST["q"], $searchText);
					$count = count($exp) - 1;
					$searchText = strip_tags($searchText);
					$searchText = substr($searchText, 0, 250) . "...";
					$searchText = str_ireplace($_POST["q"], "<strong>" . $_POST["q"] . "</strong>", $searchText);
					
					$results[] = array("link" => $tmp_link, "text" => $searchText, "name" => $searchName, "rank" => $count);
					$ranks[] = $count;
				}
				
				
			}
		}
		
		// srovname vysledky dle ranku
		if(!empty($results)) array_multisort($ranks, SORT_DESC, $results);
		
		$this->template->results = $results;		
		$this->template->query = $_POST["q"];
		$this->template->id = $id;
	}
	
}

?>